package com.bos.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;


@Controller
public class UploadController {
    //1.这边是处理文件上传的方法
    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("f1") MultipartFile file, HttpSession session) throws Exception, IOException {
        //获取tomcat的路径
        String uploadPath = session.getServletContext().getRealPath("/uploadFile/");
        System.out.println(uploadPath);
        File fileDir = new File(uploadPath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();//新建一个文件夹

        }
        //获取用户上传的文件名称
        String upFileName = file.getOriginalFilename();
        //在文件夹下创建一个对应文件名称的文件
        File newFile = new File(fileDir, upFileName);
        //将用户上传的文件写入服务器新建的文件当中
        file.transferTo(newFile);
        return "redirect:showAll";
    }

    //2.这是处理文件下载的方法
    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(@RequestParam("fileName") String fileName
            , HttpSession session) throws Exception {
        System.out.println(fileName);
        //获取tomcat下文件的存放路径
        String dirPath = session.getServletContext().getRealPath("/uploadFile/");
        //String dirPath="C:\\ruanjian\\apache-tomcat-7.0.67\\webapps\\uploadFile\\icon1.jpg";
        //获取文件名
        // String filename="反馈报告.pdf";
        //根据路径和需要下载的文件名称来获取到服务器中的文件
        File downFile = new File(dirPath, fileName);
        //判断文件是否存在
        if (!downFile.exists()) {
            System.out.println("文件未找到。。。。无法下载");
            return null;
        }
        //将文件转换为字节数组
        byte[] buffer = FileUtils.readFileToByteArray(downFile);
        //响应浏览器头文件的对象
        HttpHeaders headers = new HttpHeaders();
        String fName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        System.out.println("转换UTF-8的格式的字节长度为:" + fileName.getBytes("UTF-8").length);
        //设置浏览器以下载的形式打开该文件，文件的默认名称为用户所要下载的名称。
        headers.setContentDispositionFormData("attachment", fName);
        //构造一个响应文件下载的对象。
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(buffer, headers, HttpStatus.CREATED);
        return entity;


    }


}
